package com.open.capacity.workflow.controller;

import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.model.system.LoginAppUser;
import com.open.capacity.utils.DateUtil;
import com.open.capacity.utils.SysUserUtil;
import com.open.capacity.workflow.model.WFTask;
import com.open.capacity.workflow.service.WFProcessinstanceService;
import com.open.capacity.workflow.service.WFTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 ftquan 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 流程任务
 */
@Slf4j
@RestController
@Api(tags = "流程任务模块api")
public class WFTaskController {


    @Autowired
    private WFTaskService taskService;

    @Autowired
    private WFProcessinstanceService processinstanceService;


    /**
     * 查询流程任务
     *
     * @param keyword
     * @param startTime
     * @param endTime
     * @param categoryId
     * @return
     */
    @PreAuthorize("hasAuthority('wftask:get/wftasks')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
    })
    @GetMapping("/wftasks_all")
    @LogAnnotation(name = "流程", module = "workflow-center", recordRequestParam = false)
    public PageResult findAllTasks(@RequestParam(value = "page") Integer page,
                                @RequestParam(value = "limit") Integer limit,
                                @RequestParam(value = "keyword", required = false) String keyword,
                                @RequestParam(value = "startTime", required = false)
                                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
                                @RequestParam(value = "endTime", required = false)
                                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
                                @RequestParam(value = "categoryId", required = false) String categoryId,
                                @RequestParam(value = "departmentId", required = false) String departmentId,
                                @RequestParam(value = "schemeCode", required = false) String schemeCode,
                                @RequestParam(value = "isFinished", required = false) Integer isFinished) {
        LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isNotEmpty(departmentId)) {
            params.put("departmentId", departmentId);
        }
        if (StringUtils.isNotEmpty(keyword)) {
            params.put("keyword", keyword);
        }
        if (isFinished != null) {
            params.put("isFinished", isFinished);
        }

        params.put("startTime", startTime == null ? DateUtil.getFirstDayOfMonth(DateUtil.getYear(), DateUtil.getMonth()) : DateUtil.format(startTime));
        params.put("endTime", (endTime == null ? DateUtil.getLastDayOfMonth(DateUtil.getYear(), DateUtil.getMonth()) : DateUtil.format(endTime)));

        params.put("page", page);
        params.put("limit", limit);
        params.put("schemeCode", schemeCode);
        switch (categoryId) {
            case "1":
                //params.put("createUserid", loginUser.getId());
                return processinstanceService.pageProcessinstances(params);
            case "2":
                //params.put("createUserid", loginUser.getId());
                return processinstanceService.pageActiveTasks(loginUser, params);
            case "3":
                return processinstanceService.pageFinishedTasks(loginUser, params);
            default:
                return processinstanceService.pageProcessinstances(params);
        }
    }


    /**
     * 查询流程任务
     *
     * @param keyword
     * @param startTime
     * @param endTime
     * @param categoryId
     * @return
     */
    @PreAuthorize("hasAuthority('wftask:get/wftasks')")
    @ApiOperation(value = "查询流程")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
    })
    @GetMapping("/wftasks")
    @LogAnnotation(name = "流程", module = "workflow-center", recordRequestParam = false)
    public PageResult findTasks(@RequestParam(value = "page") Integer page,
                                @RequestParam(value = "limit") Integer limit,
                                @RequestParam(value = "keyword", required = false) String keyword,
                                @RequestParam(value = "startTime", required = false)
                                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
                                @RequestParam(value = "endTime", required = false)
                                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
                                @RequestParam(value = "categoryId", required = false) String categoryId,
                                @RequestParam(value = "schemeCode", required = false) String schemeCode,
                                @RequestParam(value = "isFinished", required = false) Integer isFinished) {
        LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isNotEmpty(keyword)) {
            params.put("keyword", keyword);
        }
        if (isFinished != null) {
            params.put("isFinished", isFinished);
        }

        params.put("startTime", startTime == null ? DateUtil.getFirstDayOfMonth(DateUtil.getYear(), DateUtil.getMonth()) : DateUtil.format(startTime));
        params.put("endTime", (endTime == null ? DateUtil.getLastDayOfMonth(DateUtil.getYear(), DateUtil.getMonth()) : DateUtil.format(endTime)));

        params.put("page", page);
        params.put("limit", limit);
        params.put("schemeCode", schemeCode);
        switch (categoryId) {
            case "1":
                params.put("createUserid", loginUser.getId());
                return processinstanceService.pageProcessinstances(params);
            case "2":
                params.put("createUserid", loginUser.getId());
                return processinstanceService.pageActiveTasks(loginUser, params);
            case "3":
                return processinstanceService.pageFinishedTasks(loginUser, params);
            default:
                return processinstanceService.pageProcessinstances(params);
        }
    }


    /**
     * 更新流程状态
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('wftask:post/wftasks/{id}/updateStatus' )")
    @PostMapping(value = "/wftasks/{id}/updateStatus")
    @LogAnnotation(name = "流程", module = "workflow-center", recordRequestParam = false)
    public Result updateStatus(@PathVariable(value = "id") String id, Integer status) {
        LoginAppUser currentUser = SysUserUtil.getLoginAppUser();
        taskService.updateStatus(id, status, currentUser.getId(), currentUser.getUserName());
        return Result.succeed(null, "更新成功");
    }


    /**
     * 撤销流程
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('wftask:delete/wftasks/{id}')")
    @ApiOperation(value = "撤销流程")
    @PostMapping("/wftasks/revoke/{id}")
    @LogAnnotation(name = "流程", module = "workflow-center", recordRequestParam = false)
    public Result revoke(@PathVariable(value = "id") String id) {
        try {
            processinstanceService.revoke(id, -1);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            log.error(e.toString());
            return Result.failed("操作失败");
        }
    }

    /**
     * 删除流程实例
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('wftask:delete/wftasks/{id}')")
    @ApiOperation(value = "撤销流程")
    @DeleteMapping("/wftasks/delete/{id}")
    @LogAnnotation(name = "流程", module = "workflow-center", recordRequestParam = false)
    public Result delete(@PathVariable(value = "id") String id) {
        try {
            processinstanceService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            log.error(e.toString());
            return Result.failed("操作失败");
        }
    }

    /**
     * 判断当前用户是否用审批权限
     *
     * @param id
     */
    @GetMapping(value = "/wftasks/{id}/checkPermission")
    public Result checkPermission(@PathVariable(value = "id") String id) {
        LoginAppUser currentUser = SysUserUtil.getLoginAppUser();
        boolean flag = processinstanceService.hasPermission(id, currentUser);
        return Result.succeed(flag, "获取成功");
    }

}
